package com.wawayaya.util;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;
import android.util.Log;

import com.wawayaya.bean.SupportFileStatus;
import com.wawayaya.bookreader.bean.Pagesdata;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.io.OutputStream;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 文件操作工具包
 *
 */
public class FileUtil {

	private final static String IREADCKCSLASH = "wawayayareader/";
	private static String m_ssprimarysdcardpath = null;
	public final static String SUPPORTFILESTATUS = "support_file.stu";
	private final static String LOCALSTROKEDATA = ".stroke";
	private final static String LOCALDICTFOLDER = ".lcdc";
	private final static String LOCALDICTFILE = "lddc.d";
	private final static String LOCALDICTFILE_EN = "ldde.d";

    /**
	 * 写文本文件 在Android系统中，文件保存在 /data/data/PACKAGE_NAME/files 目录下
	 * 
	 * @param context
	 * @param
	 */
	public static void write(Context context, String fileName, String content) {
		if (content == null)
			content = "";

		try {
			FileOutputStream fos = context.openFileOutput(fileName,
					Context.MODE_PRIVATE);
			fos.write(content.getBytes());

			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 读取文本文件
	 * 
	 * @param context
	 * @param fileName
	 * @return
	 */
	public static String read(Context context, String fileName) {
		try {
			FileInputStream in = context.openFileInput(fileName);
			return readInStream(in);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String readInStream(InputStream inStream) {
		try {
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[512];
			int length = -1;
			while ((length = inStream.read(buffer)) != -1) {
				outStream.write(buffer, 0, length);
			}

			outStream.close();
			inStream.close();
			return outStream.toString();
		} catch (IOException e) {
			Log.i("FileTest", e.getMessage());
		}
		return null;
	}

	public static File createFile(String folderPath, String fileName) {
		File destDir = new File(folderPath);
		if (!destDir.exists()) {
			destDir.mkdirs();
		}
		return new File(folderPath, fileName + fileName);
	}

	/**
	 * 向手机写图片
	 * 
	 * @param buffer
	 * @param folder
	 * @param fileName
	 * @return
	 */
	public static boolean writeFile(byte[] buffer, String folder,
			String fileName) {
		boolean writeSucc = false;

		boolean sdCardExist = Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);

		String folderPath = "";
		if (sdCardExist) {
			folderPath = Environment.getExternalStorageDirectory()
					+ File.separator + folder + File.separator;
		} else {
			writeSucc = false;
		}

		File fileDir = new File(folderPath);
		if (!fileDir.exists()) {
			fileDir.mkdirs();
		}

		File file = new File(folderPath + fileName);
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(file);
			out.write(buffer);
			writeSucc = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return writeSucc;
	}

	/**
	 * 根据文件绝对路径获取文件名
	 * 
	 * @param filePath
	 * @return
	 */
	public static String getFileName(String filePath) {
		if (StringUtils.isEmpty(filePath))
			return "";
		return filePath.substring(filePath.lastIndexOf(File.separator) + 1);
	}

	/**
	 * 根据文件的绝对路径获取文件名但不包含扩展名
	 * 
	 * @param filePath
	 * @return
	 */
	public static String getFileNameNoFormat(String filePath) {
		if (StringUtils.isEmpty(filePath)) {
			return "";
		}
		int point = filePath.lastIndexOf('.');
		return filePath.substring(filePath.lastIndexOf(File.separator) + 1,
				point);
	}

	/**
	 * 获取文件扩展名
	 * 
	 * @param fileName
	 * @return
	 */
	public static String getFileFormat(String fileName) {
		if (StringUtils.isEmpty(fileName))
			return "";

		int point = fileName.lastIndexOf('.');
		return fileName.substring(point + 1);
	}

	/**
	 * 获取文件大小
	 * 
	 * @param filePath
	 * @return
	 */
	public static long getFileSize(String filePath) {
		long size = 0;

		File file = new File(filePath);
		if (file != null && file.exists()) {
			size = file.length();
		}
		return size;
	}

	/**
	 * 获取文件大小
	 * 
	 * @param size
	 *            字节
	 * @return
	 */
	public static String getFileSize(long size) {
		if (size <= 0)
			return "0";
		java.text.DecimalFormat df = new java.text.DecimalFormat("##.##");
		float temp = (float) size / 1024;
		if (temp >= 1024) {
			return df.format(temp / 1024) + "M";
		} else {
			return df.format(temp) + "K";
		}
	}

	/**
	 * 转换文件大小
	 * 
	 * @param fileS
	 * @return B/KB/MB/GB
	 */
	public static String formatFileSize(long fileS) {
		java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
		String fileSizeString = "";
		if (fileS < 1024) {
			fileSizeString = df.format((double) fileS) + "B";
		} else if (fileS < 1048576) {
			fileSizeString = df.format((double) fileS / 1024) + "KB";
		} else if (fileS < 1073741824) {
			fileSizeString = df.format((double) fileS / 1048576) + "MB";
		} else {
			fileSizeString = df.format((double) fileS / 1073741824) + "G";
		}
		return fileSizeString;
	}

	/**
	 * 获取目录文件大小
	 * 
	 * @param dir
	 * @return
	 */
	public static long getDirSize(File dir) {
		if (dir == null) {
			return 0;
		}
		if (!dir.isDirectory()) {
			return 0;
		}
		long dirSize = 0;
		File[] files = dir.listFiles();
		for (File file : files) {
			if (file.isFile()) {
				dirSize += file.length();
			} else if (file.isDirectory()) {
				dirSize += file.length();
				dirSize += getDirSize(file); // 递归调用继续统计
			}
		}
		return dirSize;
	}

	/**
	 * 获取目录文件个数
	 * 
	 * @param
	 * @return
	 */
	public long getFileList(File dir) {
		long count = 0;
		File[] files = dir.listFiles();
		count = files.length;
		for (File file : files) {
			if (file.isDirectory()) {
				count = count + getFileList(file);// 递归
				count--;
			}
		}
		return count;
	}

	public static byte[] toBytes(InputStream in) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int ch;
		while ((ch = in.read()) != -1) {
			out.write(ch);
		}
		byte buffer[] = out.toByteArray();
		out.close();
		return buffer;
	}

	/**
	 * 检查文件是否存在
	 * 
	 * @param name
	 * @return
	 */
	public static boolean checkFileExists(String name) {
		boolean status;
		if (!name.equals("")) {
			File path = Environment.getExternalStorageDirectory();
			File newPath = new File(path.toString() + name);
			status = newPath.exists();
		} else {
			status = false;
		}
		return status;
	}

	/**
	 * 检查路径是否存在
	 * 
	 * @param path
	 * @return
	 */
	public static boolean checkFilePathExists(String path) {
		return new File(path).exists();
	}

	/**
	 * 计算SD卡的剩余空间
	 * 
	 * @return 返回-1，说明没有安装sd卡
	 */
	public static long getFreeDiskSpace() {
		String status = Environment.getExternalStorageState();
		long freeSpace = 0;
		if (status.equals(Environment.MEDIA_MOUNTED)) {
			try {
				File path = Environment.getExternalStorageDirectory();
				StatFs stat = new StatFs(path.getPath());
				long blockSize = stat.getBlockSize();
				long availableBlocks = stat.getAvailableBlocks();
				freeSpace = availableBlocks * blockSize / 1024;
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			return -1;
		}
		return (freeSpace);
	}

	/**
	 * 新建目录
	 * 
	 * @param directoryName
	 * @return
	 */
	public static boolean createDirectory(String directoryName) {
		boolean status;
		if (!directoryName.equals("")) {
			File path = Environment.getExternalStorageDirectory();
			File newPath = new File(path.toString() + directoryName);
			status = newPath.mkdir();
			status = true;
		} else
			status = false;
		return status;
	}

	/**
	 * 检查是否安装SD卡
	 * 
	 * @return
	 */
	public static boolean checkSaveLocationExists() {
		String sDCardStatus = Environment.getExternalStorageState();
		boolean status;
		if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)) {
			status = true;
		} else
			status = false;
		return status;
	}
	
	/**
	 * 检查是否安装外置的SD卡
	 * 
	 * @return
	 */
	public static boolean checkExternalSDExists() {
		
		Map<String, String> evn = System.getenv();
		return evn.containsKey("SECONDARY_STORAGE");
	}

	/**
	 * 删除目录(包括：目录里的所有文件)
	 * 
	 * @param fileName
	 * @return
	 */
	public static boolean deleteDirectory(String fileName) {
		boolean status;
		SecurityManager checker = new SecurityManager();
		
		if (!fileName.equals("")) {

			File path = Environment.getExternalStorageDirectory();
			File newPath = new File(path.toString() + fileName);
			checker.checkDelete(newPath.toString());
			if (newPath.isDirectory()) {
				String[] listfile = newPath.list();
				try {
					for (int i = 0; i < listfile.length; i++) {
						File deletedFile = new File(newPath.toString() + "/"
								+ listfile[i].toString());
						deletedFile.delete();
					}
					newPath.delete();
					TLog.log("DirectoryManager deleteDirectory", fileName);
					status = true;
				} catch (Exception e) {
					e.printStackTrace();
					status = false;
				}

			} else
				status = false;
		} else
			status = false;
		return status;
	}

	/**
	 * 删除文件
	 * 
	 * @param fileName
	 * @return
	 */
	public static boolean deleteFile(String fileName) {
		boolean status;
		SecurityManager checker = new SecurityManager();

		if (!fileName.equals("")) {

			File path = Environment.getExternalStorageDirectory();
			File newPath = new File(path.toString() + fileName);
			checker.checkDelete(newPath.toString());
			if (newPath.isFile()) {
				try {
					TLog.log("DirectoryManager deleteFile", fileName);
					newPath.delete();
					status = true;
				} catch (SecurityException se) {
					se.printStackTrace();
					status = false;
				}
			} else
				status = false;
		} else
			status = false;
		return status;
	}

	/**
	 * 删除空目录
	 * 
	 * 返回 0代表成功 ,1 代表没有删除权限, 2代表不是空目录,3 代表未知错误
	 * 
	 * @return
	 */
	public static int deleteBlankPath(String path) {
		File f = new File(path);
		if (!f.canWrite()) {
			return 1;
		}
		if (f.list() != null && f.list().length > 0) {
			return 2;
		}
		if (f.delete()) {
			return 0;
		}
		return 3;
	}

	/**
	 * 重命名
	 * 
	 * @param oldName
	 * @param newName
	 * @return
	 */
	public static boolean reNamePath(String oldName, String newName) {
		File f = new File(oldName);
		return f.renameTo(new File(newName));
	}

	/**
	 * 删除文件
	 * 
	 * @param filePath
	 */
	public static boolean deleteFileWithPath(String filePath) {
		SecurityManager checker = new SecurityManager();
		File f = new File(filePath);
		checker.checkDelete(filePath);
		if (f.isFile()) {
			TLog.log("DirectoryManager deleteFile", filePath);
			f.delete();
			return true;
		}
		return false;
	}
	
	/**
	 * 清空一个文件夹
	 * @param
	 */
	public static void clearFileWithPath(String filePath) {
		List<File> files = FileUtil.listPathFiles(filePath);
		if (files.isEmpty()) {
			return;
		}
		for (File f : files) {
			if (f.isDirectory()) {
				clearFileWithPath(f.getAbsolutePath());
			} else {
				f.delete();
			}
		}
	}

	/**
	 * 获取SD卡的根目录
	 * 
	 * @return
	 */
	public static String getSDRoot() {
		
		return Environment.getExternalStorageDirectory().getAbsolutePath();
	}
	
	/**
	 * 获取手机外置SD卡的根目录
	 * 
	 * @return
	 */
	public static String getExternalSDRoot() {
		
		Map<String, String> evn = System.getenv();
		
		return evn.get("SECONDARY_STORAGE");
	}

	/**
	 * 列出root目录下所有子目录
	 * 
	 * @param
	 * @return 绝对路径
	 */
	public static List<String> listPath(String root) {
		List<String> allDir = new ArrayList<String>();
		SecurityManager checker = new SecurityManager();
		File path = new File(root);
		checker.checkRead(root);
		// 过滤掉以.开始的文件夹
		if (path.isDirectory()) {
			for (File f : path.listFiles()) {
				if (f.isDirectory() && !f.getName().startsWith(".")) {
					allDir.add(f.getAbsolutePath());
				}
			}
		}
		return allDir;
	}
	
	/**
	 * 获取一个文件夹下的所有文件
	 * @param root
	 * @return
	 */
	public static List<File> listPathFiles(String root) {
		List<File> allDir = new ArrayList<File>();
		SecurityManager checker = new SecurityManager();
		File path = new File(root);
		checker.checkRead(root);
		File[] files = path.listFiles();
		for (File f : files) {
			if (f.isFile())
				allDir.add(f);
			else 
				listPath(f.getAbsolutePath());
		}
		return allDir;
	}

	public enum PathStatus {
		SUCCESS, EXITS, ERROR
	}

	/**
	 * 上一层目录
	 * @param sfolder
	 * @return
	 */
	public static String getparentfolder(String sfolder) {
		if(TextUtils.isEmpty(sfolder)){
			return null;
		}
		int ipos = sfolder.lastIndexOf(File.separator);
		if(ipos > 0){
			return sfolder.substring(0, ipos);
		}
		return sfolder;
	}

	/**
	 * 创建目录
	 * 
	 * @param
	 */
	public static PathStatus createPath(String newPath) {
		File path = new File(newPath);
		if (path.exists()) {
			return PathStatus.EXITS;
		}
		if (path.mkdir()) {
			return PathStatus.SUCCESS;
		} else {
			return PathStatus.ERROR;
		}
	}

	/**
	 * 截取路径名
	 * 
	 * @return
	 */
	public static String getPathName(String absolutePath) {
		int start = absolutePath.lastIndexOf(File.separator) + 1;
		int end = absolutePath.length();
		return absolutePath.substring(start, end);
	}

	/**
	 * 获取应用程序缓存文件夹下的指定目录
	 * @param context
	 * @param dir
	 * @return
	 */
	public static String getAppCache(Context context, String dir) {
		String savePath = context.getCacheDir().getAbsolutePath() + "/" + dir + "/";
		File savedir = new File(savePath);
		if (!savedir.exists()) {
			savedir.mkdirs();
		}
		savedir = null;
		return savePath;
	}


	/**
	 * 获取 sdcard路径
	 * @param binternalsdcard   storage/sdcard1  storage/sdcard0
	 * @return
	 */
	private static String getsdcardpath(boolean binternalsdcard) {
		if(null == m_ssprimarysdcardpath) {
			boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
			if(sdCardExist)  {
				m_ssprimarysdcardpath = Environment.getExternalStorageDirectory().getAbsolutePath();
			}
		}
		if(binternalsdcard) {
			return m_ssprimarysdcardpath;
		}
		String spathes[] = getpossibleexternalsdcardpath();
		if(!TextUtils.isEmpty(m_ssprimarysdcardpath)){
			if(TextUtils.isEmpty(spathes[0]) || !spathes[0].contentEquals(m_ssprimarysdcardpath)){
				TLog.log("utils : getsdcardpath : " + spathes[0] + " != " + m_ssprimarysdcardpath);
			}
		}
		if(TextUtils.isEmpty(spathes[1])){
			return m_ssprimarysdcardpath;
		}
		return spathes[1];
	}

	/**
	 * 剩余空间
	 * @param spath
	 * @return
	 */
	private static long getsdcardFreeSpaceUnitMB(String spath) {
		if(TextUtils.isEmpty(spath)) {
			return 0;
		}
		try {
			StatFs sf = new StatFs(spath);
			long lbs = sf.getBlockSize();
			long lab = sf.getAvailableBlocks();
			return lbs * lab / 1024 / 1024;  // bytes to mbs
		} catch (Exception e) {
		}
		return 0;
	}

	/**
	 * 获得可用的sdcard path
	 * @return
	 */
	private static String[] getpossibleexternalsdcardpath() {
		String[] sspossiblepath = new String[2];
		sspossiblepath[0] = null;
		sspossiblepath[1] = null;
		String sdprimary = System.getenv("EXTERNAL_STORAGE");
		if(null!= sdprimary){
			sspossiblepath[0] = sdprimary;
		}
		String sdssecondary = System.getenv("SECONDARY_STORAGE");
		if(!TextUtils.isEmpty(sdssecondary)){
			String[] secondarys = sdssecondary.split(":");
			if(null != secondarys){
				for (String path : secondarys) {
					File file = new File(path);
					if (file.isDirectory() && file.canWrite() && file.canRead()) {
						sspossiblepath[1] = path;
						break;
					}
				}
			}
		}
		return sspossiblepath;
	}

	/**
	 * 对指定路径 的文件进行反序列化
	 * @param spath
	 * @return
	 */
	private static Object readSerializedObject(String spath) {
		ObjectInputStream ois = null;
		Object obj = null;
		try {
			ois = new ObjectInputStream(new FileInputStream(spath));
		} catch (StreamCorruptedException se) {
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
		} catch (Exception e) {
		}
		try {
			obj = ois.readObject();
		} catch (OptionalDataException e) {
		} catch (ClassNotFoundException e) {
		} catch (IOException e) {
		} catch (Exception e) {
		}
		try {
			if(null != ois) {
				ois.close();
			}
		} catch (IOException e) {
		} catch (Exception e) {
		}
		return obj;
	}

	/**
	 * 删除 wawayayareader 下所有的文件
	 */
	public static void deleteRelativeFolers() {
		String  sdcardpath="";
		File folder = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
		if(sdCardExist)  {
			sdcardpath = Environment.getExternalStorageDirectory().getAbsolutePath();
			TLog.log("deleteold  1 sdcardpath " + sdcardpath);
		}

		if (!TextUtils.isEmpty(sdcardpath)) {
			String tempfoldepath = sdcardpath + File.separator + IREADCKCSLASH;
			folder = new File(tempfoldepath);
			if (folder != null && folder.exists() && folder.isDirectory()) {
				TLog.log("deleteold  11  sdcardpath " + tempfoldepath);
				deleteDir(folder);
			}
		}
		String[] spathes = getpossibleexternalsdcardpath();
		for (String path : spathes) {
			if (!TextUtils.isEmpty(path)) {
				String tempfoldepath = path + File.separator + IREADCKCSLASH;
				TLog.log("deleteold  2 path " + tempfoldepath);
				folder = new File(tempfoldepath);
				if (folder != null && folder.exists() && folder.isDirectory()) {
					TLog.log("deleteold  22 path " + tempfoldepath);
					deleteDir(folder);
				}
			}
		}
	}

	public static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();//递归删除目录中的子目录下
			for (int i=0; i<children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		// 目录此时为空，可以删除
		return dir.delete();
	}

	public static void clearDirorFile(File fdir) {
		if(null == fdir) {
			return;
		}
		File[] fs = fdir.listFiles();
		if(null != fs) {
			for(File f : fs) {
				clearDirorFile(f);
				f.delete();
			}
		}
	}

	/**
	 * 根据指定名称建立文件夹
	 *  for example:  storage/sdcard1/wawayayareader/
	 * @param binternalsdcard
	 * @return
	 * @throws Exception
	 */
	public static String getireadckcsdcardpath(boolean binternalsdcard) throws Exception {
		String spath = getsdcardpath(binternalsdcard)+"/";
		String sckcpath = spath + IREADCKCSLASH;
		/** 判断是否有可用空间*/
		if(getsdcardFreeSpaceUnitMB(spath) <= Constants.MINIMIZE_FREESPACE) {
			// less than 1000MB
			throw new Exception(Constants.ERROR_LACKOFFREESPACE);
		}
		File file = new File(sckcpath);
		if (!file.exists()) {
			file.mkdirs();
		}
		return sckcpath;
	}

	/*** book reader  start **/
	/***
	 *   for example: /sdcard/wawayayareader/.stroke
	 * @param binternalsdcard
	 * @return
	 * @throws Exception
	 */
	public static String getireadckclocalstrokedatafolder(boolean binternalsdcard) throws Exception {

		String spath = getireadckcsdcardpath(binternalsdcard) + LOCALSTROKEDATA;
		new File(spath).mkdirs();

		return spath;
	}
	// for example: storage/sdcard1/wawayayareader/.lcdc/lddc.d
	public static String getireadckclocaldictionarypath(String sparentfolder, boolean english) throws Exception {
		if(TextUtils.isEmpty(sparentfolder)){
			return null;
		}
		sparentfolder += (sparentfolder.endsWith(File.separator) ? "" : File.separator) + LOCALDICTFOLDER;
		new File(sparentfolder).mkdirs();
		TLog.log("ReaderPath dictpath = " + sparentfolder + File.separator + LOCALDICTFILE);
		if (english) {
			return sparentfolder + File.separator + LOCALDICTFILE_EN;
		} else {
			return sparentfolder + File.separator + LOCALDICTFILE;
		}
	}

	// for example: storage/sdcard1/wawayayareader/.lcdc
	public static String getireadckclocaldictionaryfolder(String sparentfolder) throws Exception {
		if(TextUtils.isEmpty(sparentfolder)){
			return null;
		}
		sparentfolder += (sparentfolder.endsWith(File.separator) ? "" : File.separator) + LOCALDICTFOLDER;
		new File(sparentfolder).mkdirs();
		return sparentfolder;
	}

	/**
	 * support文件是否已经下载
	 * @param ct
	 * @param key
	 * @return
	 */
	public static boolean checkSupportDownload(Context ct,final String  key) {
		String path = "";
		try {
			path = getireadckclocalstrokedatafolder(true);
			path += (File.separator+key+SUPPORTFILESTATUS);
			File stufile = new File(path);
			if (stufile.exists()) {
				SupportFileStatus status = new SupportFileStatus();
				status = (SupportFileStatus)readSerializedObject(path);
				if (status != null) {
					return status.isDownloadFinished();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 *  文件的反序列化 Pagesdata
	 * @param spartpath
	 * @return
	 */
	public static Pagesdata unserializebookpartpage(String spartpath) {
		TLog.log("utils : Unserializebookpartpage    ========================= : spartpath : " + spartpath);
		return (Pagesdata)readSerializedObject(spartpath);
	}

	/**
	 * 序列化 pagesdata
	 * @param ssefilepath
	 * @param pd
	 * @return
	 */
	public static boolean serializebookpartpage(String ssefilepath, Pagesdata pd){
		boolean bdone = false;
		if(null != pd) {
			ObjectOutputStream oos = openserializedstream(ssefilepath);
			if(null != oos) {
				bdone = flushendserializeddata(oos, pd);
				if(!bdone) {
					try{
						new File(ssefilepath).delete();
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			}
		}
		return bdone;
	}

	private static ObjectOutputStream openserializedstream(String spath) {
		boolean bsucc = false;
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(new FileOutputStream(spath));
			bsucc = true;
		} catch (FileNotFoundException fe) {
			TLog.error("utils : getserializeddata : fe : " + fe);
		} catch (IOException ioe) {
			TLog.error("utils : getserializeddata : ioe : " + ioe);
		} catch (Exception e) {
			TLog.error("utils : getserializeddata : e : " + e);
		} finally {
			if(!bsucc && null != oos) {
				try {
					oos.close();
				} catch (IOException e) {
				}catch (Exception e) {
				}
				oos = null;
			}
		}
		return oos;
	}
	private static boolean flushendserializeddata(ObjectOutputStream oos, Object obj) {
		boolean b = false;
		if(null != oos && null != obj)
			try {
				oos.writeObject(obj);
				b = true;
			} catch (IOException oe) {
				TLog.error("utils : flushendserializeddata : oe : " + oe);
			}catch (Exception e) {
				TLog.error("utils : flushendserializeddata : e : " + e);
			}
		try {
			oos.close();
		} catch (IOException e) {
		}catch (Exception e) {
		}
		return b;
	}
	/*** book reader  end  **/

	/**
	 *
	 * @param context
	 * @param filename
	 */
	public static  void  copyArrestToDB(Context context,String  filename){
		try {
			String  databasepath = context.getDatabasePath("cobub_ums").getAbsolutePath();

			databasepath = databasepath.substring(0, databasepath.lastIndexOf("cobub_ums"));

			TLog.log("获取当前路径 ....."+databasepath);
			InputStream assetsDB = context.getAssets().open(filename);  //strln是assets文件夹下的文件名

			String  creatFile = databasepath+File.separator+filename;
			File file = new File(creatFile);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}

			OutputStream dbOut = new FileOutputStream(creatFile);  //strout是你要保存的文件名

			byte[] buffer = new byte[1024];
			int length;
			while ((length = assetsDB.read(buffer)) > 0) {
				dbOut.write(buffer, 0, length);
			}

			dbOut.flush();
			dbOut.close();
			assetsDB.close();
		}catch (IOException e){
			e.printStackTrace();
		}

	}

}